# encoding: utf-8

from PyQt5.Qt import *
from widget.my_window import MyWindow
import configparser
import os
from widget.info_box import InfoBox
import time
import _thread
from functools import partial
import json


class MarcAddOrEdtWindow(MyWindow):
    '''
    sqlserver配置 窗口
    '''
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setAttribute(Qt.WA_StyledBackground, False)
        # 窗口置顶
        self.setWindowModality(Qt.ApplicationModal)
        # 父窗口实例对象
        self.my_parent_window = kwargs['my_parent']
        # 窗口功能 add 新增， edt 编辑
        self.opt_name = kwargs['opt_name']
        #
        self.marc_init_sec = kwargs['marc_init_sec']
        # self.window_flag = kwargs['window_flag']
        # 窗口标题
        self.label_title = QLabel(self)
        self.label_title.resize(230, 40)
        self.label_title.setText('新增 导入方案' if self.opt_name == 'add' else '编辑 导入方案')
        self.label_title.move(10, 5)
        # print('marc_init_sec: {0}'.format(self.marc_init_sec))
        self.setup_page()

    def get_init_file_cf(self):
        cf = configparser.ConfigParser()
        print(qApp.cx_project_root + r'/init_file/init/marcfield.ini')
        cf.read(qApp.cx_project_root + r'/init_file/init/marcfield.ini')
        return cf

    def init_write(self, cf):
        cf.write(open(qApp.cx_project_root + r'/init_file/init/marcfield.ini', "w"))

    def setup_page(self):
        # 基础面板位置
        self.base_widget = QWidget(self)
        self.base_widget.setGeometry(0, 50, self.width(), self.height() - 50)

        # 第一行 ---------------------------------------------------
        self.choice_marc_label = QLabel(text='方案名称：')
        self.choice_marc_label.setFixedWidth(120)
        self.choice_marc_input = QLineEdit()
        self.choice_marc_input.setFixedWidth(300)
        self.new_line_btn = QPushButton('新增一行')
        self.new_line_btn.clicked.connect(self.add_new_line)
        row0 = QHBoxLayout()
        row0.addWidget(self.choice_marc_label)
        row0.addWidget(self.choice_marc_input)
        row0.addWidget(self.new_line_btn)
        row0.addStretch(1)  # 站位分割

        # 第三行, 初始化表格 ---------------------------------------------------
        self.table1 = QTableWidget()
        self.table1.setFixedWidth(870)
        self.table1.setFixedHeight(370)
        # 设置表格的列数为2列
        self.table1.setColumnCount(7)
        # self.table1.setVerticalHeaderLabels(["第一列", "第二列"])
        # 设置表格每列的宽度
        self.table1.setColumnWidth(0, 120)
        self.table1.setColumnWidth(1, 120)
        self.table1.setColumnWidth(2, 120)
        self.table1.setColumnWidth(3, 120)
        self.table1.setColumnWidth(4, 120)
        self.table1.setColumnWidth(5, 120)
        self.table1.setColumnWidth(6, 50)
        # self.table1.setColumnWidth(2, 80)
        # print(field_list)
        self.table1.setHorizontalHeaderLabels(["Marc字段", "分隔符1", "分隔符2", "Marc字段", "对应数据库字段名称", "是否导入", "操作"])

        # 表格监听表，如果表选择框改变，那么刷新表格
        # self.choice_func_combox.currentTextChanged.connect(self.refresh_table)
        row2 = QHBoxLayout()
        row2.addWidget(self.table1)

        # 最后一行 (底部常规按钮) ---------------------------------------------------
        self.okButton = QPushButton(text='确定')
        self.okButton.clicked.connect(self.save_marc_init)
        self.cancelButton = QPushButton(text="取消")
        self.cancelButton.clicked.connect(self.close_btn.click)
        row_last = QHBoxLayout()
        row_last.addStretch(1)  # 站位分割
        row_last.addWidget(self.okButton)
        row_last.addWidget(self.cancelButton)

        # 行插入列，并调整间隔 ---------------------------------------------------
        vbox = QVBoxLayout()
        vbox.addLayout(row0)
        vbox.addStretch(2)  # 站位分割
        # vbox.addLayout(row1)
        # vbox.addStretch(1)  # 站位分割
        vbox.addLayout(row2)
        vbox.addStretch(10)  # 站位分割
        vbox.addLayout(row_last)

        self.base_widget.setLayout(vbox)

        # 刷新表格
        self.refresh_table()

    def refresh_table(self):
        '''
        刷新表格
        :return:
        '''
        if self.opt_name != 'edt':
            return
        # 方案名称赋值
        self.choice_marc_input.setText(self.marc_init_sec)
        # 方案表格赋值
        cf = self.get_init_file_cf()
        kl = cf.get(self.marc_init_sec, "field_list")
        if not kl:
            return
        json_list = json.loads(kl)
        self.table1.setRowCount(len(json_list))
        for i, js_dict in enumerate(json_list):
            self.table1.setItem(i, 0, QTableWidgetItem(js_dict['field']))
            self.table1.setItem(i, 1, QTableWidgetItem(js_dict['indicator1']))
            self.table1.setItem(i, 2, QTableWidgetItem(js_dict['indicator2']))
            self.table1.setItem(i, 3, QTableWidgetItem(js_dict['subfield']))
            self.table1.setItem(i, 4, QTableWidgetItem(js_dict['fieldname']))
            # self.table1.setItem(i, 5, QTableWidgetItem('是' if js_dict['import'] else '否'))
            check_box = QCheckBox()
            check_box.setStyleSheet('margin-left: 55px')
            check_box.setChecked(True if js_dict['import'] == 1 else False)
            self.table1.setCellWidget(i, 5, check_box)
            delete_btn = QPushButton(text='删除')
            delete_btn.clicked.connect(partial(self.delete_one_line, i))
            self.table1.setCellWidget(i, 6, delete_btn)

    def delete_one_line(self, current_line):
        '''
        删除一行
        :return:
        '''
        # 删除当前行
        self.table1.removeRow(current_line)
        # 由于当前行删除后，当前行之后的行数就往前进了一行，删除时的索引就不正确了，所以需要重新绑定删除按钮事件
        # 重新绑定按钮删除事件
        for i in range(self.table1.rowCount()):
            self.table1.cellWidget(i, 6).disconnect()  # 解除绑定之前的事件
            self.table1.cellWidget(i, 6).clicked.connect(partial(self.delete_one_line, i))

    def add_new_line(self):
        '''
        新增一行
        :return:
        '''
        new_row_count = self.table1.rowCount() + 1
        self.table1.setRowCount(new_row_count)
        self.table1.setItem(new_row_count - 1, 0, QTableWidgetItem(''))
        self.table1.setItem(new_row_count - 1, 1, QTableWidgetItem(''))
        self.table1.setItem(new_row_count - 1, 2, QTableWidgetItem(''))
        self.table1.setItem(new_row_count - 1, 3, QTableWidgetItem(''))
        self.table1.setItem(new_row_count - 1, 4, QTableWidgetItem(''))
        check_box = QCheckBox()
        check_box.setStyleSheet('margin-left: 55px')
        self.table1.setCellWidget(new_row_count - 1, 5, check_box)
        delete_btn = QPushButton(text='删除')
        delete_btn.clicked.connect(partial(self.delete_one_line, new_row_count - 1))
        self.table1.setCellWidget(new_row_count - 1, 6, delete_btn)
        self.table1.scrollToBottom()
        print('new_row_count: {0}'.format(new_row_count))

    def save_marc_init(self):
        '''
        保存marc配置文件
        :return:
        '''
        cf = self.get_init_file_cf()
        secs = cf.sections()
        secs_len = len(secs)
        secs.remove(self.marc_init_sec)
        new_sec = self.choice_marc_input.text()
        if not new_sec:
            self.ycztmpz_box = InfoBox('请输入配置名称')
            self.ycztmpz_box.show()
            return
        elif self.table1.rowCount() == 0:
            self.ycztmpz_box = InfoBox('至少新增一条配置')
            self.ycztmpz_box.show()
            return
            # 如果存在相同文件名的配置文件，那就提示用户，然后返回
        if new_sec in secs:
            self.ycztmpz_box = InfoBox('已存在相同名称的配置')
            self.ycztmpz_box.show()
            return

        if self.opt_name == 'edt':
            # 新配置继承旧配置的排序
            order_num = cf.get(self.marc_init_sec, "order_num")

            # 删除旧配置
            cf = self.get_init_file_cf()
            cf.remove_section(self.marc_init_sec)
            self.init_write(cf)
            # 保存新配置
            self.save_marc(new_sec, order_num)

        if self.opt_name == 'add':
            new_order_num = str(secs_len-1)
            self.save_marc(new_sec, new_order_num)

        # 父窗口刷新选择combox
        self.my_parent_window.refresh_combox()

        # 定位到新选项上
        self.my_parent_window.choice_func_combox.setCurrentText(new_sec)
        # self.my_parent_window.choice_func_combox.setCurrentText(new_sec)

        # 提交后关闭窗口
        self.close()

    def save_marc(self, new_sec, order_num):
        '''
        保存 marc配置
        :return:
        '''
        if self.table1.rowCount() == 0:
            return

        marc_init_list = []
        for i in range(self.table1.rowCount()):
            marc_init = {}
            marc_init['field'] = self.table1.item(i, 0).text()
            marc_init['indicator1'] = self.table1.item(i, 1).text()
            marc_init['indicator2'] = self.table1.item(i, 2).text()
            marc_init['subfield'] = self.table1.item(i, 3).text()
            marc_init['fieldname'] = self.table1.item(i, 4).text()
            marc_init['import'] = 1 if self.table1.cellWidget(i, 5).isChecked() else 0
            marc_init_list.append(marc_init)
        marc_init_list_json = json.dumps(marc_init_list, ensure_ascii=False)
        # print(marc_init_list_json)

        cf = self.get_init_file_cf()
        cf.add_section(new_sec)
        cf.set(new_sec, "field_list", marc_init_list_json)
        cf.set(new_sec, "order_num", order_num)
        self.init_write(cf)

    def keyPressEvent(self, QKeyEvent):  # 键盘某个键被按下时调用
        '''
        按下 ESC关闭当前页
        :param QKeyEvent:
        :return:
        '''
        # 参数1  控件
        if QKeyEvent.key() == Qt.Key_Escape:  # 判断是否按下了ESC键
            self.close_btn.click()